package com.qiantu.phone.ui.dialog;

import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.getString;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.heytap.mcssdk.utils.LogUtil;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLDeviceCustomDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceCustomKeyBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.DeviceKeyChangeEvent;
import com.qiantu.phone.event.DeviceKeyNameChangeEvent;
import com.qiantu.phone.ui.activity.DeviceSettingActivity;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.activity.PanelBingingActivity;
import com.qiantu.phone.ui.activity.PanelQRResultActivity;
import com.qiantu.phone.ui.activity.SelectImageActivity;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.widget.btnview.OnBtnClickListener;
import com.qiantu.phone.widget.btnview.OnBtnLongClickListener;
import com.qiantu.phone.widget.btnview.OneTwoThreeFourSixEightNineButtonView;
import com.lxj.xpopup.core.BottomPopupView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BottomModifyKeyNameDialog extends BottomPopupView {

    private String key1;
    private String key2;
    private String key3;
    private String key4;
    private String key5;
    private String key6;
    private String key7;
    private String key8;
    private String deviceType;
    private String deviceSerialNo;
    private String roomSerialNo;
    private OneTwoThreeFourSixEightNineButtonView btnView1;
    private OneTwoThreeFourSixEightNineButtonView btnView2;
    private OneTwoThreeFourSixEightNineButtonView btnView3;
    private OneTwoThreeFourSixEightNineButtonView btnView4;
    private OneTwoThreeFourSixEightNineButtonView btnView6;
    private OneTwoThreeFourSixEightNineButtonView btnView8;
    private List<DeviceCustomKeyBean> customKeyList;
    private LinearLayout creameImageView;
    private LinearLayout batchImageView;
    private TextView tvCount;
    private BottomListDialog mBottomListDialog;
    private int remainScanTimes;
    private String currentAction; // 添加成员变量保存当前action
    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;


    public BottomModifyKeyNameDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_modify_key_name;
    }

    // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
    @Override
    protected void onCreate() {
        super.onCreate();
        initView();
    }

    private void initView() {
        EventBus.getDefault().register(this);
        btnView1 = findViewById(R.id.btn_view_1);
        btnView2 = findViewById(R.id.btn_view_2);
        btnView3 = findViewById(R.id.btn_view_3);
        btnView4 = findViewById(R.id.btn_view_4);
        btnView6 = findViewById(R.id.btn_view_6);
        btnView8 = findViewById(R.id.btn_view_8);
//        creameImageView = findViewById(R.id.icon_creame);
        batchImageView = findViewById(R.id.icon_batch);
//        tvCount = findViewById(R.id.tv_count);
        btnView1.setOnBtnClickListener(mOnBtnClickListener);
        btnView2.setOnBtnClickListener(mOnBtnClickListener);
        btnView3.setOnBtnClickListener(mOnBtnClickListener);
        btnView4.setOnBtnClickListener(mOnBtnClickListener);
        btnView6.setOnBtnClickListener(mOnBtnClickListener);
        btnView8.setOnBtnClickListener(mOnBtnClickListener);
        btnView1.setOnBtnLongClickListener(mLongClickListener);
        btnView2.setOnBtnLongClickListener(mLongClickListener);
        btnView3.setOnBtnLongClickListener(mLongClickListener);
        btnView4.setOnBtnLongClickListener(mLongClickListener);
        btnView6.setOnBtnLongClickListener(mLongClickListener);
        btnView8.setOnBtnLongClickListener(mLongClickListener);
//        tvCount.setText("今日剩余"+remainScanTimes+"次");
//        creameImageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(remainScanTimes > 0){
//                    showBottomListDialog();
//                }else{
//                    ToastUtils.show(R.string.photo_analyse_count_over);
//                }
//            }
//        });
        batchImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PanelBingingActivity.class);
                intent.putExtra("panelSerialNo",deviceSerialNo);
                intent.putExtra("bingingType",2);
                intent.putExtra("panelIndex",getKeyNum());
                getContext().startActivity(intent);
            }
        });
        updateKeyCount();
        updateCustomKey();
    }

    // 设置最大宽度，看需要而定
    @Override
    protected int getMaxWidth() {
        return super.getMaxWidth();
    }

    // 设置最大高度，看需要而定
    @Override
    protected int getMaxHeight() {
        return super.getMaxHeight();
    }

    /**
     * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
     *
     * @return
     */
    protected int getPopupWidth() {
        return 0;
    }

    /**
     * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
     *
     * @return
     */
    protected int getPopupHeight() {
        return 0;
    }

    OnBtnClickListener mOnBtnClickListener;
    public void setOnBtnClickListener(OnBtnClickListener listener) {
        mOnBtnClickListener = listener;
    }

    OnBtnLongClickListener mLongClickListener;

    public void setOnBtnLongClickListener(OnBtnLongClickListener listener) {
        mLongClickListener = listener;
    }

    private void updateKeyCount() {
        if (TextUtils.isEmpty(deviceType)) {
            return;
        }
        if (deviceType.equals(DeviceType.WALL_SWITCH1.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S1.stringType)) {
            btnView1.setVisibility(VISIBLE);
            btnView2.setVisibility(GONE);
            btnView3.setVisibility(GONE);
            btnView4.setVisibility(GONE);
            btnView6.setVisibility(GONE);
            btnView8.setVisibility(GONE);
        } else if (deviceType.equals(DeviceType.WALL_SWITCH2.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S2.stringType)) {
            btnView1.setVisibility(GONE);
            btnView2.setVisibility(VISIBLE);
            btnView3.setVisibility(GONE);
            btnView4.setVisibility(GONE);
            btnView6.setVisibility(GONE);
            btnView8.setVisibility(GONE);
        } else if (deviceType.equals(DeviceType.WALL_SWITCH3.stringType) ||  deviceType.equals(DeviceType.WALL_SWITCH_S3.stringType)) {
            btnView1.setVisibility(GONE);
            btnView2.setVisibility(GONE);
            btnView3.setVisibility(VISIBLE);
            btnView4.setVisibility(GONE);
            btnView6.setVisibility(GONE);
            btnView8.setVisibility(GONE);
        }else if (deviceType.equals(DeviceType.WALL_SWITCH4.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_J4.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S4.stringType)) {
            btnView1.setVisibility(GONE);
            btnView2.setVisibility(GONE);
            btnView3.setVisibility(GONE);
            btnView4.setVisibility(VISIBLE);
            btnView6.setVisibility(GONE);
            btnView8.setVisibility(GONE);
        } else if (deviceType.equals(DeviceType.WALL_SWITCH6.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S6.stringType)) {
            btnView1.setVisibility(GONE);
            btnView2.setVisibility(GONE);
            btnView3.setVisibility(GONE);
            btnView4.setVisibility(GONE);
            btnView6.setVisibility(VISIBLE);
            btnView8.setVisibility(GONE);
        }else if (deviceType.equals(DeviceType.WALL_SWITCH8.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_J8.stringType)) {
            btnView1.setVisibility(GONE);
            btnView2.setVisibility(GONE);
            btnView3.setVisibility(GONE);
            btnView4.setVisibility(GONE);
            btnView6.setVisibility(GONE);
            btnView8.setVisibility(VISIBLE);
        }
    }

    private void updateCustomKey() {
        String defaultName = getResources().getString(R.string.custom_name);
        key1 = defaultName;
        key2 = defaultName;
        key3 = defaultName;
        key4 = defaultName;
        key5 = defaultName;
        key6 = defaultName;
        key7 = defaultName;
        key8 = defaultName;
        if (customKeyList != null) {
            for (DeviceCustomKeyBean keyData : customKeyList) {
                switch (keyData.getKeyIndex()) {
                    case "1":
                        key1 = keyData.getKeyName();
                        break;
                    case "2":
                        key2 = keyData.getKeyName();
                        break;
                    case "3":
                        key3 = keyData.getKeyName();
                        break;
                    case "4":
                        key4 = keyData.getKeyName();
                        break;
                    case "5":
                        key5 = keyData.getKeyName();
                        break;
                    case "6":
                        key6 = keyData.getKeyName();
                        break;
                    case "7":
                        key7 = keyData.getKeyName();
                        break;
                    case "8":
                        key8 = keyData.getKeyName();
                        break;
                }
            }
        }
        btnView1.setText(key1, null);
        btnView2.setText(key1, key2);
        btnView3.setText(key1, key2, key3);
        btnView4.setText(key1, key2, key3, key4);
        btnView6.setText(key1, key2, key3, key4, key5, key6, null, null);
        btnView8.setText(key1, key2, key3, key4, key5, key6, key7, key8);
    }

    public void initCustomKeyInfo(List<DeviceCustomKeyBean> customKeyList) {
        this.customKeyList = customKeyList;
        if (btnView1 != null) {
            updateCustomKey();
        }
    }

    public void setDeviceType(String deviceType,String deviceSerialNo,String roomSerialNo) {
        this.deviceType = deviceType;
        this.deviceSerialNo = deviceSerialNo;
        this.roomSerialNo = roomSerialNo;
        if (btnView1 != null) {
            updateKeyCount();
        }
    }

    public void setRemainScanTimes(int remainScanTimes) {
        this.remainScanTimes = remainScanTimes;
//        if(tvCount != null){
//            tvCount.setText("今日剩余"+remainScanTimes+"次");
//        }
    }

    public void setCustomKeyName(String keyID, String name) {
        if (deviceType.equals(DeviceType.WALL_SWITCH1.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S1.stringType)) {
            key1 = name;
            btnView1.setText(key1, null);
        } else if (deviceType.equals(DeviceType.WALL_SWITCH2.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S2.stringType)) {
            switch (keyID) {
                case "1":
                    key1 = name;
                    break;
                case "2":
                    key2 = name;
                    break;
            }
            btnView2.setText(key1, key2);
        } else if (deviceType.equals(DeviceType.WALL_SWITCH3.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S3.stringType)) {
            switch (keyID) {
                case "1":
                    key1 = name;
                    break;
                case "2":
                    key2 = name;
                    break;
                case "3":
                    key3 = name;
                    break;
            }
            btnView3.setText(key1, key2, key3);
        } else if (deviceType.equals(DeviceType.WALL_SWITCH4.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_J4.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S4.stringType)) {
            switch (keyID) {
                case "1":
                    key1 = name;
                    break;
                case "2":
                    key2 = name;
                    break;
                case "3":
                    key3 = name;
                    break;
                case "4":
                    key4 = name;
                    break;
            }
            btnView4.setText(key1, key2, key3, key4);
        } else if (deviceType.equals(DeviceType.WALL_SWITCH6.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S6.stringType)) {
            switch (keyID) {
                case "1":
                    key1 = name;
                    break;
                case "2":
                    key2 = name;
                    break;
                case "3":
                    key3 = name;
                    break;
                case "4":
                    key4= name;
                    break;
                case "5":
                    key5 = name;
                    break;
                case "6":
                    key6 = name;
                    break;
            }
            btnView6.setText(key1, key2, key3, key4, key5, key6, null, null);
        } else if (deviceType.equals(DeviceType.WALL_SWITCH8.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_J8.stringType)) {
            switch (keyID) {
                case "1":
                    key1 = name;
                    break;
                case "2":
                    key2 = name;
                    break;
                case "3":
                    key3 = name;
                    break;
                case "4":
                    key4 = name;
                    break;
                case "5":
                    key5 = name;
                    break;
                case "6":
                    key6 = name;
                    break;
                case "7":
                    key7 = name;
                    break;
                case "8":
                    key8 = name;
                    break;
            }
            btnView8.setText(key1, key2, key3, key4, key5, key6, key7, key8);
        }
    }

    protected int getKeyNum(){
        if (deviceType.equals(DeviceType.WALL_SWITCH1.stringType)||deviceType.equals(DeviceType.WALL_SWITCH_S1.stringType)) {
            return 1;
        } else if (deviceType.equals(DeviceType.WALL_SWITCH2.stringType)  || deviceType.equals(DeviceType.WALL_SWITCH_S2.stringType)) {
            return 2;
        } else if (deviceType.equals(DeviceType.WALL_SWITCH3.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_S3.stringType)) {
            return 3;
        }else if (deviceType.equals(DeviceType.WALL_SWITCH4.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_J4.stringType)  || deviceType.equals(DeviceType.WALL_SWITCH_S4.stringType)) {
            return 4;
        } else if (deviceType.equals(DeviceType.WALL_SWITCH6.stringType)  || deviceType.equals(DeviceType.WALL_SWITCH_S6.stringType)) {
            return 6;
        }else if (deviceType.equals(DeviceType.WALL_SWITCH8.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_J8.stringType)) {
            return 8;
        }
        return 0;
    }

    private XXPermissions xxPermissions;
    private void getImage(String action) {
        currentAction = action; // 保存当前action
        if(xxPermissions == null){
            xxPermissions = XXPermissions.with(getContext());
        }
        String[] permissions;
        String permissionHint;
        
        if(SelectImageActivity.ACTION_CAMERA.equals(action)) {
            // 拍照只需要相机权限
            permissions = new String[]{Manifest.permission.CAMERA};
            permissionHint = "App需要使用您的相机权限，来拍摄面板图片进行识别分析...";
        } else {
            // 相册选择需要存储权限
            permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            permissionHint = "App需要使用您的存储权限，来选择相册中的图片进行识别分析...";
        }
        
        if(!XXPermissions.isGranted(getContext(),permissions) && AppApplication.isHuawei() ){
            showConfirmHintDialog(permissionHint);
        }else{
            requestPermission(action, permissions);
        }
    }

    private void showConfirmHintDialog(String text) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getContext())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            // 用户取消，不做任何操作
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            String[] permissions;
                            if(SelectImageActivity.ACTION_CAMERA.equals(currentAction)) {
                                permissions = new String[]{Manifest.permission.CAMERA};
                            } else {
                                permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                            }
                            requestPermission(currentAction, permissions);
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setCancelable(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void requestPermission(String action, String[] permissions) {
        xxPermissions.permission(permissions)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            actionProfilePic(action);
                        }
                    }
                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.show(R.string.common_permission_fail_1);
                    }

                });
    }

    private void actionProfilePic(String action) {
        Intent intent = new Intent(getContext(), SelectImageActivity.class);
        intent.setAction(SelectImageActivity.ACTION_SQUARE);
        intent.putExtra("ACTION", action);
        ((DeviceSettingActivity)getContext()).startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, @Nullable Intent data) {
                if (data!=null && data.getExtras()!=null){
                    //在这里获得了剪裁后的Bitmap对象，可以用于上传
                    String imagePath = data.getExtras().getString(SelectImageActivity.CROP_IMAGE_PATH);
                    String imageBase64 = encodeToBase64(imagePath);
                    analysePhoto(imageBase64);
                }
            }
        });
    }

    private String encodeToBase64(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    public void analysePhoto(String imageBase64){
        String appcode = "7de3f736442941f3aaea1a852230e06c";
        String bodys = "{\"image\":\""+imageBase64+"\",\"configure\":{\"output_prob\":true,\"output_keypoints\":false,\"skip_detection\":false,\"without_predicting_direction\":false}}";

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"),bodys);
        String baseUrl = "https://tysbgpu.market.alicloudapi.com/api/predict/ocr_general";
        Request request = new Request.Builder().header("Authorization", "APPCODE " + appcode).header("Content-Type", "application/json; charset=UTF-8").url(baseUrl).post(requestBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtil.e(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                remainScanTimes = remainScanTimes - 1;
//                tvCount.setText("今日剩余"+remainScanTimes+"次");
                reportPhotoAnalyse();
                String res = response.body().string();
                Intent intent = new Intent(getContext(), PanelQRResultActivity.class);
                intent.putExtra("type",deviceType);
                intent.putExtra("deviceSerialNo",deviceSerialNo);
                intent.putExtra("roomSerialNo",roomSerialNo);
                intent.putExtra("analyseData",res);
                getContext().startActivity(intent);
            }
        });
    }

    private void reportPhotoAnalyse(){
        LLHttpManager.reportPhotoAnalyse(this, AppApplication.getInstance().getCurrentHouseSerialNo(), new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {}

            @Override
            public void onSucceed(HttpData<Void> result) {}

            @Override
            public void onFail(Exception e) {}

            @Override
            public void onEnd(Call call) {}
        });
    }

    private void showBottomListDialog(){
        if (mBottomListDialog == null) {
            mBottomListDialog = new BottomListDialog(getContext());
            mBottomListDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(getContext());
            List<String> data = new ArrayList<>();
            data.add("从相册选择");
            data.add("照相");
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    String key = data.get(position);
                    if(key.equals("照相")){
                        getImage(SelectImageActivity.ACTION_CAMERA);
                    }else{
                        getImage(SelectImageActivity.ACTION_GALLERY);

                    }
                    mBottomListDialog.dismiss();
                }
            });
            mBottomListDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomListDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomListDialog.getAdapter();
        listLabelAdapter.setChecekSelect(true);
        mBottomListDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceKeyNameChangeEvent(DeviceKeyNameChangeEvent event) {
        customKeyList = LLDeviceCustomDBManager.getInstance(getContext()).getDataByDeviceSerialNo(deviceSerialNo);
        //设备状态推送
        updateCustomKey();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
